<template>
  <el-dialog :title="$t('tool.modelManage.' + title)" :visible.sync="dialogFormVisible" custom-class="jtyj-dialog"
    :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" label-position="top">
      <el-form-item :label="$t('tool.modelManage.chineseName')" :prop="getCurrentFormValue('name')">
        <el-input v-model="form[getCurrentFormValue('name')]" autocomplete="off" class="jtyj-input"
          :placeholder="$t('tool.others.placehoderInput')"></el-input>
      </el-form-item>
      <!-- <el-form-item
        v-if="flag != 'model'"
        :label="$t('tool.modelManage.englishName')"
        :prop="getCurrentFormValue('englishName')"
      >
        <el-input
          v-model="form[getCurrentFormValue('englishName')]"
          autocomplete="off"
          class="jtyj-input"
          :placeholder="$t('tool.others.placehoderInput')"
        ></el-input>
      </el-form-item> -->
      <!-- <el-form-item
        v-if="flag != 'model'"
        :label="$t('tool.modelManage.folderDescription')"
        :prop="getCurrentFormValue('description')"
      >
        <el-input
          v-model="form[getCurrentFormValue('description')]"
          autocomplete="off"
          class="jtyj-input"
          :placeholder="$t('tool.others.placehoderInput')"
        ></el-input>
      </el-form-item> -->
      <!-- <el-form-item :label="$t('tool.modelManage.parentFolder')">
        <treeselect
          v-model="form.parentId"
          :options="treeData"
          class="jtyj-input"
          :disabled="flag == 'dataModeling'"
        >
        </treeselect>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button class="jtyj-btn-cancel" @click="cancel">{{
        $t("setup.buttonText.cancel")
      }}</el-button>
      <el-button class="jtyj-btn-primary" @click="submitForm">{{
        $t("setup.buttonText.save")
      }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addTreeApi, updateTreeApi } from "@/api/myspace/preprocessing/index";
import { mapState } from "vuex";
export default {
  props: {
    preSetType: {
      type: Number,
      default: () => 1,
    },
  },
  data() {
    return {
      title: "",
      flag: "", // 新增文件夹的标志，判断是哪个部分的新增
      dialogFormVisible: false,
      form: {
        name: "",
        parentId: 0,
        nodeType: 1, // 树类型 0=文件, 1=文件夹
        preSetType: 1, // 预处理类型 1=镜像管理，2=在线开发运行，3=算子管理，4=任务流管理
        userId: null,
      },
      treeData: [],
      rules: {
        modelEnglishName: [
          { required: true, message: "请输入英文名称", trigger: "blur" },
        ],
        globalEnglishName: [
          { required: true, message: "请输入英文名称", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      userId: (state) => state.user.id,
    }),
  },
  mounted() {
    this.form.preSetType = this.preSetType;
  },
  methods: {
    init(sign, node, treeData, flag, id, mainVersionId) {
      this.form.preSetType = this.preSetType;
      this.dialogFormVisible = true;
      this.flag = flag;
      this.reset(treeData, id, mainVersionId);
      if (sign == "add") {
        this.title = "newFolder";
        if (node) {
          // 新增子目录
          this.form.parentId = node.id;
          this.form.modelDataType = node.data.modelDataType;
          this.form.globalDataType = node.data.globalDataType;
        }
      } else if (sign == "edit") {
        this.title = "editFolder";
        this.form.parentId = node.parentId;
        this.form.id = node.id;
        this.form.name = node.name;
        this.form.nodeType = node.nodeType;
        this.form.remark = node.remark;
      } else {
        this.title = "addFolder";
        this.form.parentId = node.parentId;

        if (flag == "account") {
          this.form.id = node.id;
          this.form.modelName = node.name;
          this.form.modelEnglishName = node.data.modelEnglishName;
          this.form.modelDescription = node.data.modelDescription;
        } else if (flag == "model") {
          this.form.fileId = node.id;
          this.form.fileName = node.name;
        } else if (flag == "dataModeling") {
          this.form.modelDataId = node.id;
          this.form.modelDataName = node.name;
          this.form.dataEnglishName = node.data.dataEnglishName;
          this.form.modelDataType = node.data.modelDataType;
          this.form.modelDataDescription = node.data.modelDataDescription;
        } else if (flag == "global") {
          this.form.globalDataId = node.id;
          this.form.globalDataName = node.name;
          this.form.globalEnglishName = node.data.globalEnglishName;
          this.form.globalDataType = node.data.globalDataType;
          this.form.globalDataDescription = node.data.globalDataDescription;
        }
      }
    },
    // 获取当前表单绑定的数据
    getCurrentFormValue(param) {
      if (this.flag == "account") {
        switch (param) {
          case "name":
            return "name";
          case "description":
            return "modelDescription";
          case "englishName":
            return "modelEnglishName";
        }
      } else if (this.flag == "dataModeling") {
        switch (param) {
          case "name":
            return "modelDataName";
          case "description":
            return "modelDataDescription";
          case "englishName":
            return "dataEnglishName";
        }
      } else if (this.flag == "global") {
        switch (param) {
          case "name":
            return "globalDataName";
          case "description":
            return "globalDataDescription";
          case "englishName":
            return "globalEnglishName";
        }
      } else if (this.flag == "model") {
        switch (param) {
          case "name":
            return "fileName";
          case "description":
            return "globalDataDescription";
          case "englishName":
            return "fileEnglishName";
        }
      }
      return ""; // 默认返回空字符串，避免未定义属性
    },
    // 将树结构数据格式化为需要的结构
    filterTreeByType(tree, type) {
      // 定义递归函数来筛选子节点
      function filterChildren(children, parentId) {
        if (!children || children.length === 0) return [];

        // 筛选出符合条件的子节点
        const filteredChildren = children
          .filter((child) => child.type === type)
          .map((child) => {
            // 递归处理子节点
            const filteredChild = {
              id: child.id,
              label: child.name,
              children: [],
              parentId: parentId,
            };
            filteredChild.children = filterChildren(child.children, child.id);
            if (filteredChild.children.length == 0) {
              delete filteredChild.children;
            }
            return filteredChild;
          });

        return filteredChildren;
      }

      // 筛选根节点
      const filteredTree = tree
        .filter((node) => node.type === type)
        .map((node) => {
          const filteredNode = {
            id: node.id,
            label: node.name,
            children: [],
            parentId: 0,
          };
          filteredNode.children = filterChildren(node.children, node.id);
          if (filteredNode.children.length == 0) {
            delete filteredNode.children;
          }
          return filteredNode;
        });

      return filteredTree;
    },
    reset(treeData, id, mainVersionId) {
      if (this.flag == "dataModeling") {
        this.treeData = this.filterTreeByType(treeData, 0);
      } else {
        this.treeData = [];
        const menu = {
          id: 0,
          label: "根目录",
          children: [],
          parentId: -1,
        };
        menu.children = this.filterTreeByType(treeData, 0);
        this.treeData.push(menu);
      }

      this.form =
        this.flag == "account"
          ? {
            name: "",
            parentId: 0,
            userId: this.userId,
            nodeType: 0,
            preSetType: this.preSetType,
          }
          : this.flag == "model"
            ? {
              fileId: null,
              fileName: null,
              parentId: 0,
              userId: null,
              nodeType: 0,
            }
            : this.flag == "global"
              ? {
                globalDataId: null,
                globalDataName: null,
                parentId: 0,
                userId: null,
                nodeType: 0,
                globalDataType: null,
              }
              : {
                modelDataId: null,
                modelDataName: null,
                parentId: 0,
                userId: null,
                nodeType: 0,
                id: id,
                mainVersion: mainVersionId,
                modelDataType: null,
              };
      this.resetForm("form");
    },
    cancel() {
      this.dialogFormVisible = false;
    },
    // 表单提交
    submitForm() {
      this.form.userId = this.userId;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id == null) {
            addTreeApi(this.form).then((response) => {
              if (response.code == 200) {
                this.$message.success(
                  this.$toolHandle.getI18nName(
                    this.$zh.setup.responseText,
                    this.$en.setup.responseText,
                    this.$i18n.locale,
                    "success"
                  )
                );
                this.$emit("refresh");
                this.dialogFormVisible = false;
              }
            });
          } else {
            updateTreeApi(this.form).then((response) => {
              if (response.code == 200) {
                this.$message.success(
                  this.$toolHandle.getI18nName(
                    this.$zh.setup.responseText,
                    this.$en.setup.responseText,
                    this.$i18n.locale,
                    "success"
                  )
                );
                this.$emit("refresh");
                this.dialogFormVisible = false;
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style></style>
